package loginProject

import (
	"fmt"
	"os"
)

var (
	userAccountKeyIn string
	userPasswdKeyIn  string
)

func JudgeUser() {

	fmt.Printf("Enter your account:")
	_, err := fmt.Scanln(&userAccountKeyIn)
	if err != nil {
		fmt.Println(err)
	}

	if JudgeExist(userAccountKeyIn, userAccountList) {
		JudgePasswd(userAccountKeyIn, userAccountList)
		WelcomeUser(userAccountKeyIn, PersonList)
		// 应用入口
	} else {
		fmt.Println("用户未注册，请先注册")
		newPersonAdd, newAccount, newPasswd := UserRegistration()
		PersonList = append(PersonList, newPersonAdd)
		userAccountList[newAccount] = newPasswd

	}

}

// 判断账户存在
func JudgeExist(userAccount string, accountList map[string]string) bool {
	for i, _ := range accountList {
		if i == userAccount {
			return true
		}
	}
	return false
}

// 判断账户密码对应性
func JudgePasswd(userAccount string, accountList map[string]string) bool {
	for judgeNum := 0; judgeNum < 3; judgeNum++ {

		fmt.Printf("Enter your password:")
		_, err2 := fmt.Scanln(&userPasswdKeyIn)
		if err2 != nil {
			fmt.Println(err2)
		}

		if userPasswdKeyIn == accountList[userAccount] {
			fmt.Println("登录成功!")
			return true
		} else {
			fmt.Printf("用户名密码错误 %d 次，请重新输入\n", judgeNum+1)
			if judgeNum == 2 {
				fmt.Println("密码输入错误三次，程序退出")
				os.Exit(1)
			}
		}
	}
	return false
}

// 欢迎语句
func WelcomeUser(userAccount string, personList []PersonInfo) {
	for num, _ := range personList {
		if userAccount == personList[num].userAccount {
			fmt.Printf("id-%d:  Welcome Mr.%s", personList[num].userId, personList[num].userName)
		}
	}
}
